package com.augrain.microframework.trace.wrapper;


import com.augrain.microframework.trace.context.TraceContext;
import com.augrain.microframework.trace.context.TraceContextSnapshot;

import java.util.concurrent.Callable;

/**
 * Callable 包装类
 *
 * @param <V> 泛型返回值参数
 * @author biaoy
 * @since 2024/12/28
 */
public class CallableWrapper<V> implements Callable<V> {

    private final Callable<V> task;

    private final TraceContextSnapshot snapshot;

    public CallableWrapper(Callable<V> task, TraceContextSnapshot snapshot) {
        this.task = task;
        this.snapshot = snapshot;
    }

    public static <V> CallableWrapper<V> of(Callable<V> callable) {
        TraceContextSnapshot snapshot = TraceContext.snapshot();
        return new CallableWrapper<>(callable, snapshot);
    }

    @Override
    public V call() throws Exception {
        if (task != null) {
            try {
                TraceContext.continued(snapshot);
                return task.call();
            } finally {
                TraceContext.clear();
            }
        }
        return null;
    }
}
